/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hk.ces.oxfam.patch.OTWTeamCoordinator;

import hk.ces.oxfam.patch.config.Config;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 *
 * @author ivanlin
 */
public class JDBCUtil
{
  private static Connection conn;
//  private static final String UAT = "jdbc:db2://localhost:5005/oxfamadm";
//  private static final String URL_155 = "jdbc:db2://192.168.193.155:50000/oxfamadm";
  private static final String PRODUCTION = "jdbc:db2://localhost:50006/oxfamadm";

  static
  {
    try
    {
      Class.forName(Config.CLASS_NAME.toString());
    }
    catch (ClassNotFoundException ex)
    {
      Logger.getLogger(JDBCUtil.class.getName()).log(Level.SEVERE, null, ex);
    }
  }

  public static Connection getConnection()
  {  
    try
    {
      if (conn == null || conn.isClosed())
      {
        conn = DriverManager.getConnection(PRODUCTION, "db2inst1", "admin");
      }
    }
    catch (SQLException ex)
    {
      Logger.getLogger(JDBCUtil.class.getName()).log(Level.SEVERE, null, ex);
    }

    return conn;
  }

  public static void close(Connection conn, PreparedStatement pst, ResultSet rs)
  {
    releaseCursor(pst, rs);
    
    try
    {
      if (conn != null)
      {
        conn.close();
      }
    }
    catch (SQLException ex)
    {
      Logger.getLogger(JDBCUtil.class.getName()).log(Level.SEVERE, null, ex);
    }
  }

  public static void releaseCursor(PreparedStatement pst, ResultSet rs)
  {
    try
    {
      if (rs != null)
      {
        rs.close();
      }
    }
    catch (SQLException ex)
    {
      Logger.getLogger(JDBCUtil.class.getName()).log(Level.SEVERE, null, ex);
    }
    finally
    {
      try
      {
        if (pst != null)
        {
          pst.close();
        }
      }
      catch (SQLException ex)
      {
        Logger.getLogger(JDBCUtil.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }

  private JDBCUtil()
  {

  }
}
